﻿using System;
using System.Drawing;
using System.IO;
using Microsoft.Xna.Framework.Content;
using Xnatlas.Serialization;

namespace Xnatlas
{
    public enum StorageType
    {
        Xml,
        Json
    }
    public class BitmapAtlas : BaseAtlas
    {
        public BitmapAtlas(int width, int height, string filePath)
            : base(width, height)
        {
            FilePath = filePath;
            Bitmap = new Bitmap(width, height);
        }

        public BitmapAtlas(string filePath, string fileName, StorageType storageType)
        {
            FilePath = filePath;
            Bitmap = new Bitmap(FilePath + fileName + ".png");

            SetSize(Bitmap.Width, Bitmap.Height);
            AtlasStore atlasStore = AtlasStoreSerializer.LoadFromFile(FilePath + fileName, storageType);
            if (atlasStore.Width != Width || atlasStore.Height != Height)
            {
                throw new InvalidOperationException("Image and store mismatch on size!");
            }

            AppendStoreBitmaps(atlasStore);
            Lock();
        }

        public string FilePath { get; set; }
        public Bitmap Bitmap { get; set; }
        public ContentManager Content { get; set; }

        public void SaveToFile(string fileName, StorageType storageType)
        {
            Bitmap.Save(FilePath + fileName + ".png");
            AtlasStore atlasStore = CreateAtlasStore();
            AtlasStoreSerializer.SaveToFile(atlasStore, FilePath + fileName, storageType);
        }

        protected override ITextureWrapper GetTextureWrapper(string name, string data)
        {
            Bitmap bitmap = LoadBitmap(name);
            return new BitmapTextureWrapper(bitmap, data);
        }

        protected override void BlitTextureToAtlas(AtlasedTexture atlasedTexture)
        {
            Bitmap bitmap = ((BitmapTextureWrapper)atlasedTexture.OriginalTexture).Bitmap;
            for (int y = 0; y < atlasedTexture.AtlasAreaRectangle.Height; y++)
            {
                for (int x = 0; x < atlasedTexture.AtlasAreaRectangle.Width; x++)
                {
                    Color color = bitmap.GetPixel(x, y);
                    Bitmap.SetPixel(x + atlasedTexture.AtlasAreaRectangle.X, y + atlasedTexture.AtlasAreaRectangle.Y, color);
                }
            }
        }

        private Bitmap LoadBitmap(string name)
        {
            string fileName = FilePath + name;
            if (File.Exists(fileName + ".jpg"))
            {
                return new Bitmap(FilePath + name + ".jpg");
            }
            else if (File.Exists(fileName + ".png"))
            {
                return new Bitmap(FilePath + name + ".png");
            }
            else
            {
                throw new InvalidOperationException("Unable to find file " + Path.GetFullPath(FilePath + name));
            }
        }
    }
}